package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.query.StatementItemQueryObject;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//import java.math.BigDecimal;
import java.math.BigDecimal;
import java.util.List;

/**
 * 服务项目服务impl
 *
 * @author RNIZ
 * @date 2021/11/13
 */
@Service
public class StatementItemServiceImpl implements IStatementItemService {
    
    @Autowired
    private StatementItemMapper statementItemMapper;
    @Autowired
    private  StatementServiceImpl statementService;
    @Override
    public TablePageInfo<StatementItem> query(StatementItemQueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<StatementItem>(statementItemMapper.selectForList(qo));
    }

    @Override
    public void saveItems(List<StatementItem> items) {
        StatementItem statementItem = items.remove(items.size() - 1);
        //前台传入的优惠金额
        BigDecimal itemPrice = statementItem.getItemPrice();
        Long statementId = statementItem.getStatementId();
        Statement statement = statementService.get(statementId);
        statementItemMapper.deleteByStatementId(statementId);
        //校验订单是否处于未结算
        if (Statement.STATUS_PAID.equals(statement.getStatus())){
            throw new BusinessException("订单已经完成了支付");
        }
        //接收总价金额
        BigDecimal totalAmount = new BigDecimal("0.00");
        //接收数量
        BigDecimal totalCount = new BigDecimal("0");
        for (StatementItem item : items) {
            System.out.println("===================="+item.getItemName());
            System.out.println("===================="+item.getStatementId());
            statementItemMapper.insert(item);
            totalAmount = totalAmount.add(item.getItemPrice().multiply(item.getItemQuantity()));
            totalCount = totalCount.add(item.getItemQuantity());
        }
        if (itemPrice.compareTo(totalAmount)>0) {
            throw new BusinessException("金额不合法");
        }
        statementService.updateBy(totalAmount,totalCount,itemPrice,statementId);
    }

    @Override
    public void deleteByStatementId(Long statementId) {
        statementItemMapper.deleteByStatementId(statementId);
    }


}
